﻿namespace TShooter.TfsSearch.EngineModel
{
    public abstract class CrawlerBase: ServiceBase, ICrawler
    {
        #region Constructors and member variables

        private IEngine _Engine;

        #endregion

        #region Abstract methods

        protected abstract DocumentReference CrawlNextItem();

        protected abstract IndexDocument FetchDocument(int id);

        #endregion

        #region ICrawler Members

        public IEngine Engine
        {
            get { return _Engine; }
            set { _Engine = value; }
        }

        public event DocumentCrawledEventHandler DocumentCrawled;

        public IndexDocument BuildDocument(int id)
        {
            return FetchDocument(id);
        }

        #endregion

        #region Overrides

        protected override bool DoService()
        {
            DocumentReference reference = CrawlNextItem();

            if (reference != null)
            {
                OnDocumentCrawled(reference);
            }

            return (reference != null);
        }

        #endregion

        #region Private methods

        protected virtual void OnDocumentCrawled(DocumentReference reference)
        {
            if (DocumentCrawled != null)
            {
                DocumentCrawled(this, new DocumentCrawledEventArgs(reference));
            }
        }

        #endregion
    }
}
